
import { RequestConfig, history} from "umi";
import { message, Modal } from 'antd'



let isModal = false;
const baseURL = 'https://api.blog.wipi.tech/';
const errorCode = {
    '400': 'Bad Request',
    '401': 'Unauthorized',
    '403': 'Forbidden',
    '404': 'Not Found',
    '500': 'Internal Server Error',
    '502': "Bad GetWay",
    '503': 'Service Unavailable'
}
// setCookie(authorization);
export const request: RequestConfig = {
    timeout: 100000,
    errorConfig: {},
    middlewares: [],
    
    // 请求拦截器
    requestInterceptors: [(url, options) => {
        const authorization = `Bearer ${JSON.parse(localStorage.getItem("token") as string)}`   ;
        if (!/https/.test(url)) {
            url = baseURL + url;
        }
        let headers = options.headers;
        if (authorization) {
            headers = { ...headers, authorization }
        }
        return {
            url,
            options: { ...options, interceptors: true, headers },
        };
    }],
    // 响应拦截器
    responseInterceptors: [async (response, options) => {
        let data = { code: 200, msg: '' };
        try {
            data = await response.clone().json();
            // 处理网络错误
            if (response.status !== 200) {
                message.error(response.statusText);
                return response;
            }
            // 处理业务错误
            if (data.code === 401) {
                if (isModal) {
                    return response;
                }
                isModal = true;
                Modal.warning({
                    title: '系统提示',
                    closable: true,
                    content: '登录状态已过期，您可以继续留在该页面，或者重新登录',
                    okText: '重新登陆',
                    cancelText: '取消',
                    onOk: () => {
                        history.replace('/login/login');
                        isModal = false;
                    }
                });
                // 处理业务错误
            } else if (data.code !== 200) {
                message.error(data.msg);
                return response;
            }
        } catch (e: any) {
            message.error(e.message);
            return response;
        }
        return response;
    }],
};

// // 覆盖根组件，把mobx的store注入
// export function rootContainer(container: React.ReactElement) {
//     return React.createElement(StoreContext.Provider, { value: store }, container);
// }

// // 导航守卫

// if(authorization1===""){
//     console.log();
    
// }
// console.log(authorization1)
    const authorization1 = JSON.parse(localStorage.getItem("token") as string) || "";
    console.log(authorization1)
    if(!authorization1){
        history.replace(`/login/login`)
    }
    // 登陆态拦截

  
